import request from '@/utils/request';
import {
    FileListParams,
    FileListResponse,
    FileType
} from '../../pages/backhub/filemgr/types';

const API_BASE_URL = '/api/files';

export const FileService = {
    /**
     * 获取文件列表
     * @param params 查询参数
     */
    getFiles: async (params: FileListParams) => {
        const { page, pageSize, fileType, keyword, path } = params;
        const queryParams = new URLSearchParams();

        queryParams.append('page', page.toString());
        queryParams.append('pageSize', pageSize.toString());

        if (fileType && fileType !== FileType.ALL) {
            queryParams.append('fileType', fileType);
        }

        if (keyword) {
            queryParams.append('keyword', keyword);
        }

        if (path) {
            queryParams.append('path', path);
        }

        try {
            const response = await request.get<FileListResponse>(
                `${API_BASE_URL}?${queryParams.toString()}`
            );
            return response;
        } catch (error) {
            throw error;
        }
    },

    /**
     * 上传文件
     * @param files 文件列表
     * @param path 上传路径
     */
    uploadFiles: async (files: File[], path: string) => {
        const formData = new FormData();

        files.forEach(file => {
            formData.append('files', file);
        });

        formData.append('path', path);

        try {
            const response = await request.post(`${API_BASE_URL}/upload`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });
            return response;
        } catch (error) {
            throw error;
        }
    },

    /**
     * 删除文件
     * @param fileIds 文件ID列表
     */
    deleteFiles: async (fileIds: string[]) => {
        try {
            const response = await request.delete(`${API_BASE_URL}`, {
                data: { fileIds }
            });
            return response;
        } catch (error) {
            throw error;
        }
    },

    /**
     * 创建文件夹
     * @param name 文件夹名称
     * @param path 创建路径
     */
    createFolder: async (name: string, path: string) => {
        try {
            const response = await request.post(`${API_BASE_URL}/folder`, {
                name,
                path
            });
            return response;
        } catch (error) {
            throw error;
        }
    },

    /**
     * 下载文件
     * @param fileId 文件ID
     */
    downloadFile: async (fileId: string) => {
        try {
            const response = await request.get(`${API_BASE_URL}/${fileId}/download`, {
                responseType: 'blob'
            });

            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;

            // 从响应头中获取文件名
            const contentDisposition = response.headers['content-disposition'];
            let filename = 'download';

            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
                if (filenameMatch && filenameMatch.length > 1) {
                    filename = filenameMatch[1];
                }
            }

            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            link.remove();

            return response;
        } catch (error) {
            throw error;
        }
    },

    /**
     * 获取文件详情
     * @param fileId 文件ID
     */
    getFileDetails: async (fileId: string) => {
        try {
            const response = await request.get(`${API_BASE_URL}/${fileId}`);
            return response;
        } catch (error) {
            throw error;
        }
    }
}; 